import {
  asyncRoutes,
  constantRoutes,
  makeSubsystemMenu,
  makeMenuRoutes,
  makeMenuRoutesKeepAlive
} from '@/router'
import {
  getAuthMenus
} from '@/api/subsystem/menu'

const state = {
  projectId: '',
  projectName: '',
  subRoutes: [],
  addSubRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addSubRoutes = routes
    state.subRoutes = routes
  },
  SET_SUB_ROJECT: (state, params) => {
    state.projectId = params.projectId
    state.projectName = params.projectName
  }
}

const actions = {
  subsystemMenus({
    commit
  }, params) {
    return new Promise((resolve, reject) => {
      getAuthMenus(params).then(rsp => {
        if (200 == rsp.code) {
          const authorizedMenuList = rsp.result
          const asyncMenuRoutes = makeSubsystemMenu(authorizedMenuList)
          asyncMenuRoutes.push(...asyncRoutes)
          constantRoutes.map(item => {
            const childrenItem = []
            if (item.path === '/subsystem') {
              if (asyncMenuRoutes.length > 0) {
                for (let i = 0; i < asyncMenuRoutes.length; i++) {
                  if(asyncMenuRoutes[i].children&&asyncMenuRoutes[i].children.length >0){
                    childrenItem.push(...asyncMenuRoutes[i].children)
                  }
                }
              }
              item.children.push(...childrenItem)
            }
          })
          const menuItem = makeMenuRoutes(authorizedMenuList)
          menuItem.push(...asyncRoutes)
          commit('SET_ROUTES', menuItem)
          resolve(constantRoutes)
        } else {
          reject(rsp.message)
        }
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
